package com.tms.app.tms.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.code19.library.VerificationUtils;
import com.tms.app.tms.R;
import com.tms.app.tms.bean.UserInfo;
import com.tms.app.tms.bean.response.UserInfoRes;
import com.tms.app.tms.ui.base.ui.AbsPhotoPickWithPs;
import com.tms.app.tms.ui.home.me.UserInfoPresenter;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.youtu.Verification;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.zafu.camera.activity.CameraIdCradActivity;

/**
 * Created by Administrator on 2017/10/27 0027.
 */

public class InfoMeActivity extends AbsPhotoPickWithPs {
    @BindView(R.id.text_scan)
    TextView textScan;
    Handler handler;
    @BindView(R.id.text_photo_number)
    EditText textPhotoNumber;
    @BindView(R.id.text_realName)
    EditText textRealName;
    @BindView(R.id.text_idcard_no)
    EditText textIdcardNo;
    @BindView(R.id.text_adress)
    EditText textAdress;
    @BindView(R.id.img_idcard_1)
    ImageView imgIdcard1;
    @BindView(R.id.img_idcard_2)
    ImageView imgIdcard2;
    @BindView(R.id.img_driver)
    ImageView imgDriver;

    int clickId = R.id.img_idcard_1;
    @BindView(R.id.button_send)
    Button buttonSend;
    private boolean isFrist = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        setToolBarTitle("个人资料", -1, 0);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Object object = msg.obj;
                switch (msg.what) {
                    case 1:
                        bindView((JSONObject) object);
                        break;
                    case 0:
                        showMsg("识别失败请重新识别");
                }
            }
        };
        presenter = new UserInfoPresenter();
        userInfo = SharePreferenceUtil.getObject(this, UserInfo.class);
        if (userInfo == null)
            userInfo = new UserInfo();
        bindDataToView(userInfo);
        findViewById(R.id.img_parent_4).setVisibility(View.GONE);
    }

    @Override
    public void initLayout() {
        setContentView(R.layout.activity_info_me);

    }

    @Override
    public List<Integer> intitImgBg() {
        List<Integer> imgResList = getImgResList();
        imgResList.add(R.mipmap.idcard_res1);
        imgResList.add(R.mipmap.idcard_res2);
        imgResList.add(R.mipmap.driver1);
        return imgResList;
    }


    private void bindView(JSONObject obj) {
        try {
            textRealName.setText(obj.getString("name"));
            textIdcardNo.setText(obj.getString("id"));
            textAdress.setText(obj.getString("address"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.text_scan, R.id.img_idcard_1, R.id.img_idcard_2, R.id.img_driver, R.id.button_send,
    R.id.img_res_1,R.id.img_res_2,R.id.img_res_3})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.text_scan:
                Intent intent = new Intent(this, CameraIdCradActivity.class);
                intent.putExtra("path", "/sdcard/");
                intent.putExtra("name", System.currentTimeMillis() + "user.jpg");
                intent.putExtra("type", "idcardFront");
                startActivityForResult(intent, 201);
                break;
            case R.id.toolbar_left:
                finish();
                break;
            case R.id.button_send:
                seveUser();
                break;
            case R.id.img_res_1:
                intent=new Intent(this,ShowPhotoActivity.class);
                intent.putExtra("imgPath" , R.mipmap.idcard_font);
                intent.putExtra("imgType",1);
                startActivity(intent);
                break;
            case R.id.img_res_2:
                intent=new Intent(this,ShowPhotoActivity.class);
                intent.putExtra("imgPath" , R.mipmap.idcard_back);
                intent.putExtra("imgType",1);
                startActivity(intent);
                break;
            case R.id.img_res_3:
                seveUser();intent=new Intent(this,ShowPhotoActivity.class);
                intent.putExtra("imgPath" , R.mipmap.driver);
                intent.putExtra("imgType",1);
                startActivity(intent);
                break;
        }
    }

    private void seveUser() {
//        UserInfo userInfo=new UserInfo();
        userInfo.setMobile(userInfo.getMobile());
        userInfo.setDriverName(textRealName.getText().toString());
        userInfo.setAddress(textAdress.getText().toString());
        userInfo.setIdNumber(textIdcardNo.getText().toString());
        if (userInfo.getDriverName() == null && userInfo.getDriverName().length() < 0) {
            showMsg("请输入姓名");
            return;
        }
        if (StringUtil.isEmpty(userInfo.getIdNumber())||userInfo.getIdNumber().length()<10) {
            showMsg("请输入身份证号");
            return;
        }
        if (userInfo.getAddress().length() < 1) {
            showMsg("请输入地址");
            return;
        }
        int imgSize = 0;
        String[] imgPath = {userInfo.getIdCardPicPositive(), userInfo.getIdCardPicNegative()
                , userInfo.getDrivingLicensePic()};
        for (String s : imgPath) {
            if (!StringUtil.isEmpty(s))
                imgSize = imgSize + 1;
        }
        for (ImageView imageView : selectImgList.keySet()) {
            if (selectImgList.get(imageView)!=null&&!selectImgList.get(imageView).equals("-1")){
                imgSize = imgSize + 1;
            }
        }
        imgSize = imgSize + selectImgList.size();
        if (imgSize < 3) {
            showMsg("请上传证件");
            return;
        }
        userInfo.idcardA = selectImgList.get(imgViewList2.get(0));
        userInfo.idcardB = selectImgList.get(imgViewList2.get(1));
        userInfo.driver = selectImgList.get(imgViewList2.get(2));
        userInfo.moveCardA = selectImgList.get(imgViewList2.get(0));
//        userInfo.moveCardB=selectImgList.get(imgViewList2.get(0));
        presenter.updateUserInfo(userInfo);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribe(UserInfoRes userInfoRes) {
        if (userInfoRes.getCode() == 200 && userInfoRes.getRequestType() == 2) {
            showMsg("保存成功");
            SharePreferenceUtil.saveObject(this, userInfo);
            finish();
            return;
        }
        if (userInfoRes.getCode() == 200) {
            bindDataToView(userInfoRes.getData());
        }
    }


    private void bindDataToView(UserInfo userInfo) {
        textIdcardNo.setText(userInfo.getIdNumber());
        textPhotoNumber.setText(userInfo.getMobile());
        textRealName.setText(userInfo.getDriverName());
        textAdress.setText(userInfo.getAddress());
        String[] imgPath = {userInfo.getIdCardPicPositive(), userInfo.getIdCardPicNegative()
                , userInfo.getDrivingLicensePic()};
        showServerImg(imgPath);
        if (userInfo.getAuth_status() == 1) {
            buttonSend.setVisibility(View.GONE);
            textIdcardNo.setEnabled(false);
            textPhotoNumber.setEnabled(false);
            textRealName.setEnabled(false);
            textAdress.setEnabled(false);
            textScan.setVisibility(View.INVISIBLE);
        }else {
            buttonSend.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==201){
            Bundle extras = data.getExtras();
            final String path = extras.getString("path");
            new Thread() {
                @Override
                public void run() {
                    JSONObject respose = null;
                    try {
                        respose = Verification.VerificationIdCardOcr(path, 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Message message = handler.obtainMessage();
                    message.what=0;
                    if (respose!=null){
                        message.what = 1;
                    }
                    message.obj = respose;
                    handler.sendMessage(message);


                }
            }.start();
        }
    }
}
